<?php

namespace app\common\model;

use app\admin\model\Admin;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
//        'paytime',
//        'sendtime',
//        'receipttime',
//        'completetime',
//        'canceltime',
    ];

    public static function init()
    {
        //新增前
        self::event('before_insert', function ($info) {
            if ( $info->parent_id<=0) {
                $set = get_set();
                //类型:0=爆品,1=捐增,2=兑换
                switch ($info['type']){
                    case 0:
                        $status = 1;
                        break;
                    case 1:
                        $status = 3;
                        break;
                    case 2:
                        $status = 6;
                        break;
                }
                $type =2;//1 收入 2 支出
                //买家扣一个福袋
                //类型:1=爆品,2=定点捐增,3=捐闲置,4=注册,5=拉人,6=兑换,7=其他
                if(!empty($info['user_id']))
                return User::send($set['conversion'],$info['user_id'],$status,$type);
            }
        });
        //更新后
        self::event('after_update', function ($info) {
            //总订单
            if ( $info->parent_id<=0) {
                $set = get_set();
                //type 类型:0=爆品,1=捐增,2=兑换
                if($info['type']==2){
                    //确认收货
                    if($info->status==4){
                        $type=1;//1 收入 2 支出
                        $status=6;// $status 类型:1=爆品,2=定点捐增,3=捐闲置,4=注册,5=拉人,6=兑换,7=其他
                        $user_id=$info['sell_id'];//卖家收福袋
                    }
                    // $status 类型:1=爆品,2=定点捐增,3=捐闲置,4=注册,5=拉人,6=兑换,7=其他
                    if(!empty($user_id))
                    return User::send($set['conversion'],$user_id,$status,$type);
                }elseif ($info['type']==1){
//                    $orderGoods = OrderGoods::where(['order_id'=>$info['id']])->find();

                    //确认收货
                    if($info->status==4){
                        $type=1;//1 收入 2 支出
                        $status=3;// $status 类型:1=爆品,2=定点捐增,3=捐闲置,4=注册,5=拉人,6=兑换,7=其他
                        $user_id=$info['sell_id'];//卖家收福袋
                    }
                    // $status 类型:1=爆品,2=定点捐增,3=捐闲置,4=注册,5=拉人,6=兑换,7=其他
                    if(!empty($user_id))
                        return User::send($set['conversion'],$user_id,$status,$type);
//                    GoodsDonate::get();
                }



                //退货退款的时候，修改商品为上架
                if($info['status']==6 || $info['status']==7){
                    $orderGoods = OrderGoods::where(['order_id'=>$info['id']])->select();

                    if(!empty($orderGoods) ){
                        foreach ($orderGoods as $kk=>$vv){
                            switch ($vv['type']){
                                case 0:
                                    $goods = Goods::get($vv['goods_id']);
                                    break;
                                case 1:
                                    $goods = GoodsDonate::get($vv['goods_id']);
                                    break;
                                case 2:
                                    $goods = Goods1::get($vv['goods_id']);
                                    break;
                            }
//                            dump($vv['goods_id']);
//                            dump($vv['type']);
//                            dd($goods);
                            if(!empty($goods)){
                                $goods->state=1;
                                $goods->save();
                            }
                        }
                    }




                    if ($info['status']==6){
                        //退货
                        $type=1;
                        $status=7;
                        $user_id =$info['user_id'];//买家退福袋

                    }elseif ($info['status']==7){
                        //订单取消
                        $type=1;
                        $status=7;
                        $user_id =$info['user_id'];//买家退福袋
                    }
                    // $status 类型:1=爆品,2=定点捐增,3=捐闲置,4=注册,5=拉人,6=兑换,7=其他
                    if(!empty($user_id))
                        return User::send($set['conversion'],$user_id,$status,$type);
                }









            }
        });

    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function address()
    {
        return $this->belongsTo('order_address', 'address_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function shop()
    {
        return $this->hasOne('shop_apply', 'id', 'sell_id', [], 'LEFT')->setEagerlyType(0);
    }



    public function orderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_id', 'id');
    }
    public function order_goods()
    {
        return $this->hasMany('OrderGoods', 'order_id', 'id');
    }
    public function getModeList()
    {
        return ['1' => __('Mode 1'), '2' => __('Mode 2')];
    }


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4'), '5' => __('Status 5'), '6' => __('Status 6'), '7' => __('Status 7')];
    }

    public function getPaytimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['paytime'] ? $data['paytime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getSendtimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['sendtime'] ? $data['sendtime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getReceipttimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['receipttime'] ? $data['receipttime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCompletetimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['completetime'] ? $data['completetime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCanceltimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['canceltime'] ? $data['canceltime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getCreateTimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['createtime'] ? $data['createtime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getSamplingTimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['samplingtime'] ? $data['samplingtime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getDetectionTimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['detectiontime'] ? $data['detectiontime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getReportTimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['reporttime'] ? $data['reporttime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getSenddetectionTimeAttr($value, $data)
    {
        $value = $value ? $value : ($data['senddetectiontime'] ? $data['senddetectiontime'] : '');
        return $value ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setSendtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setReceipttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCompletetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getMaterialAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['material']) ? $data['material'] : '');
        if(!$value){return [];}
        $value=explode(',',$value);
        foreach ($value as $k=>&$v){
            $v=get_app_image_url($v);
        }
        return $value;
    }
    /**
     * 获取数据
     * */
    public static function getlist($where=[]){

        $list = self::where($where)
            ->with(['shop','order_goods'])
            ->order('order.id desc')
//            ->fetchSql()
            ->paginate();
//        dd($list);
        foreach ($list as $k=>$v){
            $v->getRelation('shop')->visible(['company_name','logo','city1','city','id']);
            foreach ($v['order_goods'] as $vv){
                $vv->visible(['goods_name','images','thumbnailimage','goods_num','goods_price','sku_name','type','goods_id','goods_type','evaluate','gid','sku_id']);
                if($vv['type']==0){
                    $goods = Goods::where(['id'=>$vv['goods_id']])->find();
                    $vv['goods_type'] = $goods['type'];
                }
                $vv['thumbnailimage'] = $vv['images'];
                $vv['gid'] = $vv['goods_id'];
            }
            $v['is_status']=0;
            if(!empty($v['earnest']) && !empty($v['end_price'])){
                //尾款支付时间
                if(!$v['end_pricetime']){
                    $v['is_status']=2;//未支付尾款
                }
                //定金支付时间
                if(!$v['earnesttime']){
                    $v['is_status']=1;//未支付定金
                }
            }
            $v->shop->city= $v->shop->city1;
            //是否售后
//            $OrderRefund = OrderRefund::where([''])->select();
        }
        return $list;
    }

    /**
     * 订单详情
     * */
    public static function getInfo($id){
        $where['order.id']=$id;
        $info = self::where($where)
            ->with(['shop','order_goods','address'])
            ->find();
        $info->getRelation('shop')->visible(['company_name','logo','city1','city','id']);
        $info->getRelation('address')->visible(['name','phone','province','city','area','address']);
        foreach ($info['order_goods'] as $vv){
//            dd($vv);
            $vv->visible(['goods_name','images','goods_num','goods_price','sku_name','type','goods_id','goods_type','evaluate','sku_id','gid','thumbnailimage']);
            if($vv['type']==0){
                $goods = Goods::where(['id'=>$vv['goods_id']])->find();
                $vv['goods_type'] = $goods['type'];

            }
            $vv['gid'] = $vv['goods_id'];
            $vv['thumbnailimage'] = $vv['images'];
        }
        $info->shop->city= $info->shop->city1;

        if(!empty($info['earnest']) && !empty($info['end_price'])){
            //尾款支付时间
            if(!$info['end_pricetime']){
                $info['is_status']=2;//未支付尾款
            }
            //定金支付时间
            if(!$info['earnesttime']){
                $info['is_status']=1;//未支付定金
            }
        }

        return $info;
    }
    /**
     * 开票详情
     * */
    public function order_invoice($order_id){
        $where['order_id'] = $order_id;
        $info = OrderInvoice::where($where)->find();
        return $info;
    }

    /**
     * 通过商品id增加订单信息
     * */
    public static function orderGoodsAdd($info,$thisOrderId,$types){

        $orderGoods['order_id'] = $thisOrderId;
//        $orderGoods['sku_id'] = $info['id'];
        $orderGoods['goods_id'] = $info['id'];
//        $orderGoods['sku_name'] = $info['sku_name'];
        $orderGoods['goods_num'] = 1;
//        $orderGoods['goods_price'] = $info['price'];
        $orderGoods['images'] = $info['thumbnailimage'];
        $orderGoods['goods_name'] = $info['name'];
        $orderGoods['type'] = $types;
        $info = OrderGoods::create($orderGoods);

        return $info;
    }
//    /**
//     * 根据商品id获取订单商品
//     * */
//    public static function getOrderGoods($goods_id){
//        $where['goods_id'] = $goods_id;
//        OrderGoods::where()
//            ->find();
//    }
//    public static function del($id){
//        return self::destroy($id);
//    }

}
